package com.minimvc.core
{

	import com.minimvc.interfaces.IMediator;
	import com.minimvc.interfaces.IView;
	
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	/**
	 * 视图中介注册管理器;
	 * @author crl
	 * 
	 */
	[ExcludeClass]
	public class View extends EventDispatcher implements IView
	{
		protected const SINGLETON_MSG	: String = "View Singleton already constructed!";
		
		protected var mediatorMap : Dictionary;
		
		
		public function View( )
		{
			if (instance != null) throw Error(SINGLETON_MSG);
			instance = this;
			mediatorMap = new Dictionary();
			initializeView();	
		}
		
		protected function initializeView(  ) : void 
		{
		}
		
		protected static var instance	: IView;
		public static function getInstance() : IView 
		{
			if ( instance == null ) instance = new View( );
			return instance;
		}

		public function registerMediator( mediator:IMediator ) : void
		{
			var name:String = mediator.getName() ;
			if ( mediatorMap[ name ] != null ) {
				return;
			}
			mediatorMap[ name ] = mediator;
				
			var interests:Dictionary = mediator.eventInterests;
		
			for(var eventType:String in interests){
				this.addEventListener(eventType,interests[eventType],false,0,true);
			}
			mediator.onRegister();
		}


		public function getMediator( mediatorName:String ) : IMediator
		{
			return mediatorMap[ mediatorName ];
		}

		public function removeMediator( mediatorName:String ) : IMediator
		{
			var mediator:IMediator = mediatorMap[ mediatorName ] as IMediator;
			
			if ( mediator ) 
			{
				
				var interests:Dictionary = mediator.eventInterests;
				for(var eventType:String in interests){
					this.removeEventListener(eventType,interests[eventType]);
				}
				
				mediatorMap[ mediatorName ]=null;
				delete mediatorMap[ mediatorName ];
				mediator.onRemove();
			}
			
			return mediator;
		}
		
		public function hasMediator( mediatorName:String ) : Boolean
		{
			return mediatorMap[ mediatorName ] != null;
		}

		
	}
}